package com.ac.config;

import com.base.annotation.GroupUseridDataAuth;
import com.base.context.Context;
import com.base.context.ContextHolder;
import com.base.context.IUser;
import com.base.helper.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author mzl
 * @date 2022/1/20
 */
@Aspect
@Component
public class GroupUseridDataAspect {

    private Logger logger = LoggerFactory.getLogger(GroupUseridDataAspect.class);

    @Pointcut("execution(public * com.ac.api.*.controller.*.*(..))")
    public void dataAuth() {
    }

    @Around("dataAuth()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        Boolean dataAuth = groupAuth(joinPoint);
        if(!dataAuth){
           return new Result<>(false,"数据资源访问失败","你没有权限访问该资源");
        }
        return joinPoint.proceed();
    }

    private Boolean groupAuth(ProceedingJoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method              targetMethod = methodSignature.getMethod();
        GroupUseridDataAuth auth         = targetMethod.getAnnotation(GroupUseridDataAuth.class);
        if (auth != null) {
            Context context     = ContextHolder.currentContext();
            IUser currentUser = context.currentUser();
            Integer  grouptype   = Integer.parseInt(currentUser.getGrouptype());
            if(2==grouptype){
                /** 请求参数 */
                Integer userid = (Integer)joinPoint.getArgs()[0];
                if(!currentUser.getId().equals(userid)){
                    return false;
                }
            }
        }
        return true;
    }


}
